/**
 * @file led.c
 * @author chushang (email:chushangcs@163.com)
 * @brief 实现LED初始化，点亮，熄灭，翻转，闪烁
 * @version 1.2
 * @date 2025-06-04
 *
 * @copyright Copyright (c) 2025
 *
 */

#include "led.h"
#include "stdlib.h"

static LED     led_instance[LED_MAX_NUM];
static uint8_t led_idx = 0;

/**
 * @brief 注册按键实例
 *
 * @param lc [in] 按键配置结构体指针，利用该结构体进行配置
 * @return 按键实例
 */
LED *LED_Register(LEDConfig *lc)
{
    if (led_idx >= LED_MAX_NUM || lc == NULL)
    {
        return NULL;
    }

    LED *l       = &led_instance[led_idx++];
    l->gpio_port = lc->gpio_port;
    l->gpio_pin  = lc->gpio_pin;

    return l;
}

// LED_Init()已弃用
// /**
//  * @brief 初始化按键实例
//  *
//  * @param lc [in] 按键配置结构体指针，利用该结构体进行配置
//  * @return 按键实例
//  */
// void LED_Init(LED *l, LEDConfig *lc)
// {
//     memset(l, 0, sizeof(LED));
//     l->gpio_port = lc->gpio_port;
//     l->gpio_pin = lc->gpio_pin;
// }

/**
 * @brief 设置led的状态，点亮或熄灭
 *
 * @param led [out] led示例
 * @param ls  [in]  待被设置的状态
 */
void LED_SetState(LED *led, LEDState ls)
{
    if (led != NULL)
        led->state = ls;
}

/**
 * @brief 点亮LED
 *
 * @param led [in] LED实例
 */
void LED_On(LED *led)
{
    // led->state = LED_ON;
    LED_SetState(led, LED_ON);
#error "pleasre use LED driver function here, such as HAL_GPIO_WritePin"
    HAL_GPIO_WritePin(led->gpio_port, led->gpio_pin, GPIO_PIN_RESET);
}

/**
 * @brief 熄灭LED
 *
 * @param led [in] LED实例
 */
void LED_Off(LED *led)
{
    // led->state = LED_OFF;
    LED_SetState(led, LED_OFF);
#error "pleasre use LED driver function here, such as HAL_GPIO_WritePin"
    HAL_GPIO_WritePin(led->gpio_port, led->gpio_pin, GPIO_PIN_SET);
}

/**
 * @brief LED周期闪烁
 * @note 请确保该函数被调用在循环中,以确保无限闪烁
 *
 * @param led [in] 实例
 * @param period_ms [in] 闪烁周期
 */
void LED_Twinkle(LED *led, uint16_t period_ms)
{
// led->state = !led->state;
#error "pleasre use LED driver function here, such as HAL_GPIO_WritePin"
    HAL_GPIO_WritePin(led->gpio_port, led->gpio_pin, led->state);
#error invoke your delay function here
    // your_delay_function();
}

/**
 * @brief LED反转
 *
 * @param led [in] 实例
 */
void LED_Toggle(LED *led)
{
    led->state = !led->state;
#error "pleasre use LED driver function here, such as HAL_GPIO_WritePin"
    HAL_GPIO_WritePin(led->gpio_port, led->gpio_pin, led->state);
}

/**
 * @brief 检查每个LED的状态，并进行正确的操作
 *
 * @note 你可以将该函数放在主循环中，也可以自主控制LED的状态
 *
 */
void LED_Tick(void)
{
    for (uint8_t i = 0; i < led_idx; i++)
    {
        if (led_instance[i].state == LED_ON)
        {
            LED_On(&led_instance[i]);
        }
        else if (led_instance[i].state == LED_OFF)
        {
            LED_Off(&led_instance[i]);
        }
    }
}
